package com.jfinal.plugin.enjoyloader;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.setting.Setting;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.IPlugin;
import com.jfinal.template.Engine;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class EnjoyLoaderPlugin implements IPlugin {

    protected Logger logger = LogManager.getLogger(getClass().getName());

    private Engine engine;

    private String configPath = "config/enjoy.txt";

    public EnjoyLoaderPlugin(Engine engine){
        this.engine = engine;
    }

    public EnjoyLoaderPlugin(Engine engine, String configPath){
        this.engine = engine;
        this.configPath = configPath;
    }

    public boolean start() {
        /* 加载配置文件 */
        try {
            Setting config = new Setting(configPath);
            /**/
            if(engine !=null){
                /**/
                String[] sharedMethod = null;
                if(StrKit.notBlank(config.getStr("sharedMethod"))){
                    sharedMethod = config.getStrings("sharedMethod");
                }
                if(sharedMethod!=null){
                    for(String cls : sharedMethod){
                        try {
                            Class _class = Class.forName(cls.trim());
                            engine.addSharedMethod(_class.newInstance());
                            logger.debug("[EnjoyLoaderPlugin] 添加方法类 {} 成功",cls);
                        } catch (Exception e1) {
                            logger.error("[EnjoyLoaderPlugin] 加载 sharedMethod 方法失败，method : {} \r\n {}",cls, ExceptionUtil.getMessage(e1));
                        }
                    }
                }
                /**/
                String[] sharedFunction = null;
                if(StrKit.notBlank(config.getStr("sharedFunction"))){
                    sharedFunction = config.getStrings("sharedFunction");
                }
                if(sharedFunction!=null){
                    for(String function : sharedFunction){
                        engine.addSharedFunction(function);
                        logger.debug("[EnjoyLoaderPlugin] 添加模板 {} 成功",function);
                    }
                }
                return true;
            }else{

            }
        }catch (Exception e){
            logger.error("[EnjoyLoaderPlugin] 未发现配置文件 {}",configPath);
        }
        return false;
    }

    public boolean stop() {
        return false;
    }
}
